<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Collection\Common;
use App\Http\Controllers\Admin\Collection\DataBase;
use App\Http\Controllers\Admin\Collection\FiveEight;
use App\Http\Controllers\Admin\Collection\Tzzp;
use App\Http\Requests\Admin\Collection\CollectionAccountRequest;
use App\Http\Requests\Admin\Collection\CollectionRequest;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Collection\CollectionCompany;
use App\Models\Admin\Collection\CollectionLogin;
use App\Models\Admin\Collection\CollectionResume;
use App\Models\Admin\Collection\CollectionResumeCheck;
use App\Models\Admin\Collection\CollectionResumeOther;
use App\Models\Admin\Collection\CollectionResumeWorks;
use App\Models\Admin\Collection\CollectionResumeWorksImg;
use App\Models\Admin\Collection\CollectionTrackResume;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Models\Personal\PersonalUser;
use App\Models\Personal\Resume;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\Admin\Collection\CollectionResumeCertificate;
use App\Models\Admin\Collection\CollectionResumeEducation;
use App\Models\Admin\Collection\CollectionResumeLanguageSkill;
use App\Models\Admin\Collection\CollectionResumeProjectExp;
use App\Models\Admin\Collection\CollectionResumeSkill;
use App\Models\Admin\Collection\CollectionResumeWorkExp;

use Style;

class CollectionController extends CommonController{


    //采集简历----------------------------------------------------------------------------------------------------------
    /**
     * 添加简历采集网址
     * @param Request $request
     */
    public function resumeAdd(Request $request){
        //获取快速采集登录列表
        if(!empty($request->action)){
            switch($request->action){
                case '58':
                    $source = '58.com';
                    break;
                case 'tzzp':
                    $source = 'tzzp.com';
                    break;
                default:
                    $source = '';
            }
            $collectionLogin = CollectionLogin::where('source', $source)->where('type', '1')->take(10)->orderBy('updated_at')->get();
        }else{
            $collectionLogin = CollectionLogin::where('type', '1')->take(10)->orderBy('updated_at')->get();
        }
        return Style::view('admin.collection.resumeAdd', compact('collectionLogin', 'action'));
    }

    /**
     * 去除已存在简历
     * @param Request $request
     */
    public function resumeDel(Request $request){
        $pagenum = 10;
        $page = !empty($request->page) ? $request->page : 1;
        $offset = ($page - 1) * $pagenum;
        $collectionResume = CollectionResume::select('id', 'mobile')
            ->where('mobile', '!=', '')
            ->orderBy('show_type', '1')
            ->orderBy('id', 'asc')
            ->skip($offset)->take($pagenum)
            ->get();
        if(count($collectionResume) <= 0){
            echo "<a href=" . url('admin/resume_list') . ">返回采集列表</a><br>";
            exit('完成');
        }
        foreach($collectionResume as $v){
            //判断默认简历手机号码是不是已经存在
            $resumeInfo = Resume::where('mobile', $v->mobile)->where('default', '1')->first(['id', 'mobile']);
            if(empty($resumeInfo)){
                $resumeInfo = Resume::where('mobile', $v->mobile)->where('default', '!=', '1')->orderBy('updatetime', 'desc')->first(['id', 'mobile']);
            }
            if(!empty($resumeInfo)){
                //更新临时库采集数据为添加至正式库
                CollectionResume::where('id', $v->id)->update(['show_type' => 3]);
                //检查简历采集跟踪表是不是存在
                $collectionTrackResume = CollectionTrackResume::where('real_resume_id', $resumeInfo->id)->first(['id']);
                if(empty($collectionTrackResume)){
                    CollectionTrackResume::where('resume_id', $v->id)->update(['real_resume_id' => $resumeInfo->id]);
                }
            }else{
                //判断用户手机号码是不是已经存在
                $personalUser = PersonalUser::where('mobile', $v->mobile)->first(['uid', 'mobile']);
                //获取当前更新的正式库简历ID
                if(!empty($personalUser)){
                    $resume = Resume::where('uid', $personalUser->uid)->where('default', 1)->first(['id']);
                    if(!empty($resume)){
                        //更新临时库采集数据为添加至正式库
                        CollectionResume::where('id', $v->id)->update(['show_type' => 3]);
                        //检查简历采集跟踪表是不是存在
                        $collectionTrackResume = CollectionTrackResume::where('real_resume_id', $resume->id)->first(['id']);
                        if(empty($collectionTrackResume)){
                            CollectionTrackResume::where('resume_id', $v->id)->update(['real_resume_id' => $resume->id]);
                        }
                    }
                }
            }
            //最后插入更新跟踪表
            $collectionTrackResume = CollectionTrackResume::where('resume_id', $v->id)->where('real_resume_id', '!=', null)->first(['id', 'real_resume_id', 'source']);
            if(!empty($collectionTrackResume)){
                //是不是已经插入
                $collectionResumeCheck = CollectionResumeCheck::where('resume_id', $collectionTrackResume->real_resume_id)->first(['id']);
                if(empty($collectionResumeCheck)){
                    $data['resume_id'] = $collectionTrackResume->real_resume_id;
                    $data['source'] = $collectionTrackResume->source;
                    $data['created_at'] = date('Y-m-d H:i:s', time());
                    //插入真实简历ID到采集简历更新跟踪表
                    CollectionResumeCheck::create($data);
                }
            }
        }
        //跳转页面
        $this->location('admin/resume_del', $page);
    }

    /**
     * 删除临时简历
     * @param Request $request
     */
    public function delTmpResume(Request $request){
        $resume_id = $request->input('selected_id.*');
        $resume_id = array_unique($resume_id);
        foreach($resume_id as $v){
            CollectionResumeWorkExp::where('resume_id', $v)->delete();
            CollectionResumeProjectExp::where('resume_id', $v)->delete();
            CollectionResumeEducation::where('resume_id', $v)->delete();
            CollectionResumeLanguageSkill::where('resume_id', $v)->delete();
            CollectionResumeSkill::where('resume_id', $v)->delete();
            CollectionResumeCertificate::where('resume_id', $v)->delete();
            CollectionResumeOther::where('resume_id', $v)->delete();
            CollectionResumeWorks::where('resume_id', $v)->delete();
            CollectionResumeWorksImg::where('resume_id', $v)->delete();
            CollectionTrackResume::where('resume_id', $v)->delete();
            CollectionResume::where('id', $v)->delete();
        }
        flash('批量删除简历成功！', 'success');
        return redirect()->back();
    }

    /**
     * 跳转页面
     * @param $locationRoute
     * @param $page
     */
    public function location($locationRoute, $page){
        echo "0.1秒后采集第" . $page . '批数据<br>';
        echo "<a href=" . url('admin/resume_list') . ">返回采集列表</a><br>";
        $page++;
        echo '<script language="javascript" type="text/javascript">';
        echo 'setTimeout(function(){window.location.href="' . url($locationRoute) . '?page=' . $page . '";},100);';
        echo '</script>';
    }

    /**
     * 输出验证码
     * @return mixed
     */
    public function imageGif(Request $request){
        switch($request->action){
            case  'tzzp' :
                $img_code = getCurlCon('http://www.tzzp.com/ValidateCode.aspx');
                break;
            default :
                $img_code = '';
        }
        return response($img_code)->header('Content-Type', 'image/gif');
    }

    /**
     * 开始采集简历
     * @param Request $request
     */
    public function startResume(CollectionRequest $request){
        if(!empty($request->page) && $request->page > 30){
            return redirect('admin/resume_add');
        }
        $coll_url = !empty($request->url) ? $request->url : '';//采集的地址
        $page = (!empty($request->page) && $request->page <= 30) ? $request->page : 1;//采集的页数
        $resumeArr = [];
        //58同城-----------------------------------------------------------------------------------------------------------
        if(strstr($coll_url, "58.com")){
            //存储cookie文件(58同城的cookie)
            $cookie = 'cookie_58.txt';
            //检查用户是不是和上个用户相同
            if(!empty($request->username) && !Common::checkUsername($request->username, '58.com', 1)){
                @unlink(storage_path() . '/app/cookie/' . $cookie);//删除cookie
            };
            //检查有没有登录用户
            $check_url = 'https://my.58.com/index/?pp=topbar/';
            $check_login = getCurlCon($check_url, $cookie);
            if(empty($check_login)){
                $username = $request->username;//用户名
                $password = $request->password;//密码
                //登录58同城
                $login_url = 'https://passport.58.com/login/dologin?flclick=true';//登录地址
                $post_fields = 'source=pc-login&path=http%3A%2F%2Fmy.58.com%2F%3Fpts%3D1493866903712&password=' . $password . '&timesign=&isremember=false&callback=successFun&yzmstate=&fingerprint=87BC65A34C16AC1522DFB544B6A17AE8AF16ED2472C94B5A_011&finger2=zh-CN%7C24%7C1%7C4%7C1920_1080%7C1920_1040%7C-480%7C1%7C1%7C1%7Cundefined%7C1%7Cunknown%7CWin32%7Cunknown%7C5%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7C0_false_false%7Cd41d8cd98f00b204e9800998ecf8427e%7C0d66682378fa3ba7947bdbf9d38c4d4d&tokenId=2096933179&username=' . $username . '&validcode=&vcodekey=&btnSubmit=%E7%99%BB%E5%BD%95%E4%B8%AD...';
                getCurlCon($login_url, $cookie, $post_fields, 'POST'); //调用curl保存登录信息
                $check_login = getCurlCon($check_url, $cookie);//设置登录信息
                //添加账号快速登录表
                if(!empty($check_login)){
                    Common::fastLogin($coll_url, $username, $password, '58.com', 1);
                }
            };
            //用户是不是已经登录成功
            if(!empty($check_login)){
                //获取58同城简历列表数据信息 //自定义简历采集列表url地址
                if(preg_match("/(.*)\/pn(\d)+(.*?)/Uis", $coll_url, $arr1)){
                    $list_url = trim($arr1[1], '/') . '/pn' . $page . '/';
                }else{
                    $list_url = trim($coll_url, '/') . '/pn' . $page . '/';
                }
                $listData = getCurlCon($list_url, $cookie);

                //获取简历id和简历详情信息
                $resumeInfo = FiveEight::getResumeInfo($listData);
                if($resumeInfo == 'error'){
                    $err_msg = '对不起，采集列表信息出错!';
                    return Style::view('errors.collection', compact('err_msg'));
                }
                //全部工作地区 （匹配相似度）----------------------------------------------------------
                $collArea = CollArea::getAreaAll();
                //循环简历信息列表
                if(count($resumeInfo) > 0){
                    $resumeArr = [];
                    foreach($resumeInfo as $k => $v){
                        $resumeUrl = 'http://' . $v['resumeUrl']; //url简历地址
                        sleep(1);//延迟1秒在页面输出内容
                        //检查简历是不是已经存在
                        if(!DataBase::checkResume($v['resumeId'], '58')){
                            //采集简历数据
                            $arrayCon = FiveEight::resumeCon($v['resumeId'], $resumeUrl, $cookie, $collArea);
                            if($arrayCon == 'err'){
                                continue;//该简历信息可能不存在了
                            }
                            //插入简历数据到临时表
                            $insertData = DataBase::insertResume($arrayCon, '58',$page);
                            $resumeArr[] = $insertData;
                        }else{
                            //更新简历
                            $updateData = DataBase::updateResume($v['resumeId'], $resumeUrl, '58', $cookie, $collArea);
                            $resumeArr[] = $updateData;
                            //简历存在时，加入采集简历更新跟踪表
                            DataBase::addResumeCheck($v['resumeId'], $resumeUrl, '58',$page);
                        }
                    }
                }
            }else{
                $err_msg = '采集信息出错！登陆用户名或者密码错误，或者该简历信息可能不存在！';
                return Style::view('errors.collection', compact('err_msg'));
            }
            //台州招聘网-----------------------------------------------------------------------------------------------------------
        }else if(strstr($coll_url, "tzzp.com")){
            //存储cookie文件(台州招聘的cookie)
            $cookie = 'cookie_tzzp.txt';
            //检查用户是不是和上个用户相同
            if(!empty($request->username) && !Common::checkUsername($request->username, 'tzzp.com', 1)){
                @unlink(storage_path() . '/app/cookie/' . $cookie);//删除cookie
            };
            //检查有没有登录用户
            $check_url = 'http://www.tzzp.com/CcCompany/Index.aspx';
            $check_login = getCurlCon($check_url, $cookie);
            if(!preg_match("/<li>\s*<span class=\"username\">(.*)<\/span>\s*<\/li>/Uis", $check_login, $arr1)){
                $username = $request->username;//用户名
                $password = $request->password;//密码
                //$validatecode = $request->validatecode;//验证码
                //$post_fields = 'action=CompanyloginNew&userName=' . $username . '&userPwd=' . $password . '&chkComWeek=false&validatecode=' . $validatecode;
                //登录台州招聘
                $login_url = 'http://www.tzzp.com/WebService/PersonHandler.ashx';//登录地址
                $post_fields = 'action=Companylogin&userName=' . $username . '&userPwd=' . $password . '&chkComWeek=false';
                getCurlCon($login_url, $cookie, $post_fields, 'POST'); //调用curl保存登录信息
                $check_login = getCurlCon($check_url, $cookie);//设置登录信息
                //添加账号快速登录表
                if(preg_match("/<li>\s*<span class=\"username\">(.*)<\/span>\s*<\/li>/Uis", $check_login, $arr1)){
                    Common::fastLogin($coll_url, $username, $password, 'tzzp.com', 1);
                }
            }
            //用户是不是已经登录成功
            if(preg_match("/<li>\s*<span class=\"username\">(.*)<\/span>\s*<\/li>/Uis", $check_login, $arr1)){
                //获取台州招聘简历列表数据信息 //自定义简历采集列表url地址
                if(preg_match("/(.*)\/page_(\d)+(.*?)/Uis", $coll_url, $arr1)){
                    $list_url = trim($arr1[1], '/') . '/page_' . $page . '.html';
                }else{
                    $list_url = trim($coll_url, '/') . '/page_' . $page . '.html';
                }
                $listData = getCurlCon($list_url, $cookie);
                //获取简历id和简历详情信息
                $resumeInfo = Tzzp::getResumeInfo($listData);
                if($resumeInfo == 'error'){
                    $err_msg = '对不起，采集列表信息出错!';
                    return Style::view('errors.collection', compact('err_msg'));
                }
                //全部工作地区 （匹配相似度）----------------------------------------------------------
                $collArea = CollArea::getAreaAll();
                //循环简历信息列表
                if(count($resumeInfo) > 0){
                    $resumeArr = [];
                    foreach($resumeInfo as $k => $v){
                        $resumeUrl = $v['resumeUrl']; //url简历地址
                        //sleep(1);//延迟1秒在页面输出内容
                        //检查简历是不是已经存在
                        if(!DataBase::checkResume($v['resumeId'], 'tzzp')){
                            //采集简历数据
                            $arrayCon = Tzzp::resumeCon($v['resumeId'], $resumeUrl, $cookie, $collArea);
                            if($arrayCon == 'err'){
                                continue;//该简历信息可能不存在了
                            }
                            //插入简历数据到临时表
                            $insertData = DataBase::insertResume($arrayCon, 'tzzp',$page);
                            $resumeArr[] = $insertData;
                        }else{
                            //更新简历
                            $updateData = DataBase::updateResume($v['resumeId'], $resumeUrl, 'tzzp', $cookie, $collArea);
                            $resumeArr[] = $updateData;
                            //简历存在时，加入采集简历更新跟踪表
                            DataBase::addResumeCheck($v['resumeId'], $resumeUrl, 'tzzp',$page);
                        }
                        //break;//每页采集一条退出
                    }
                }

            }else{
                $err_msg = '采集信息出错！登陆用户名或者密码错误，或者该简历信息可能不存在！';
                return Style::view('errors.collection', compact('err_msg'));
            }
        }else{
            $err_msg = '对不起，登陆用户名或者密码错误，或者该用户登录不成功！';
            return Style::view('errors.collection', compact('err_msg'));
        }
        $page = $page + 1;//跳转下一页
        $secs = 3;//几秒跳转
        return Style::view('admin.collection.resumeInfo', compact('page', 'secs', 'list_url', 'resumeArr'));
    }

    /**
     * 临时采集简历列表
     * @param Request $request
     * @return mixed
     */
    public function resumeList(Request $request){
        $page = !empty($request->page) ? $request->page : '1';
        $collectionResume = CollectionResume::select('id', 'name', 'sex', 'birthday', 'education', 'mobile', 'intentionjobs', 'regtime')
            ->where('show_type', 1)
            ->orderBy('regtime', 'desc')
            ->paginate(20);
        if(count($collectionResume) > 0){
            foreach($collectionResume as $v){
                $v->sex = ($v->sex == 1) ? '男' : (($v->sex == 2) ? '女' : '');//性别
                $v->education = (!empty($v->education)) ? CollOption::getOptionName($v->education, 'education') : '';//学历
//                $v->regtime = substr($v->regtime, 0, 10);//学历
            }
        }
        return Style::view('admin.collection.resumeList', compact('collectionResume', 'page'));
    }

    /**
     * 已添加正式库简历列表
     * @param Request $request
     * @return mixed
     */
    public function formalResumeList(Request $request){
        $adminUser = auth()->guard()->user();
        $input = arrayFilter($request->only(['admin_id', 'start_time', 'end_time']));
        $admin_id = (!empty($input['admin_id'])) ? $input['admin_id'] : $adminUser->id;

        $resume = DB::table('resume as t1')
            ->join('personal_users as t2', 't1.uid', '=', 't2.uid')
            ->join('collection_track_resume as t3', 't1.id', '=', 't3.real_resume_id')
            ->join('admin_users as t4', 't4.id', '=', 't3.admin_id')
            ->select(
                't1.id', 't1.name', 't1.sex', 't1.birthday', 't1.mobile', 't1.intentionjobs', 't1.education', 't1.regtime',
                't2.last_login_ip', 't2.last_login_time',
                't4.id as admin_id,t4.name'
            )->where(function($query) use ($input, $admin_id){
                if(strlen($admin_id) > 0){
                    $query->where('t4.id', $admin_id);
                }
            })->where(function($query) use ($input){
                if(!empty($input['start_time'])){
                    $start_time = !empty($input['start_time']) ? date('Y-m-d 00:00:00', strtotime($input['start_time'])) : date('Y-m-d 00:00:00', time());
                    $end_time = !empty($input['end_time']) ? date('Y-m-d 23:59:59', strtotime($input['end_time'])) : date('Y-m-d 23:59:59', time());
                    $query->where('t1.regtime', '>=', $start_time)
                        ->where('t1.regtime', '<=', $end_time);
                }
            })
            ->orderBy('t1.updatetime', 'desc')
            ->paginate(20);
        if(count($resume) > 0){
            foreach($resume as $v){
                $v->sex = ($v->sex == 1) ? '男' : (($v->sex == 2) ? '女' : '');//性别
            }
        }
        $adminInfo = AdminUser::select('id', 'name')->get();
        //获取有效简历数量
        $resumeCount = DB::table('resume as t1')
            ->join('personal_users as t2', 't1.uid', '=', 't2.uid')
            ->join('collection_track_resume as t3', 't1.id', '=', 't3.real_resume_id')
            ->join('admin_users as t4', 't4.id', '=', 't3.admin_id')
            ->select('t1.id')
            ->where(function($query) use ($input, $admin_id){
                if(strlen($admin_id) > 0){
                    $query->where('t4.id', $admin_id);
                }
            })
            ->where(function($query) use ($input){
                if(!empty($input['start_time'])){
                    $start_time = !empty($input['start_time']) ? date('Y-m-d 00:00:00', strtotime($input['start_time'])) : date('Y-m-d 00:00:00', time());
                    $end_time = !empty($input['end_time']) ? date('Y-m-d 23:59:59', strtotime($input['end_time'])) : date('Y-m-d 23:59:59', time());
                    $query->where('t1.regtime', '>=', $start_time)
                        ->where('t1.regtime', '<=', $end_time);
                }
            })
            ->where(function($query){
                $query->where('t2.last_login_ip', '!=', '127.0.0.1')
                    ->where('t2.last_login_ip', '!=', '')
                    ->where('t2.last_login_time', '!=', null);
            })
            ->count();
        //分页分配参数 过滤boolean假值
        $appends = arrayFilter($input);
        $start_time = !empty($request->start_time) ? $request->start_time : "";
        $end_time = !empty($request->end_time) ? $request->end_time : "";
        return Style::view('admin.collection.formalResumeList', compact('resume', 'admin_id', 'adminInfo', 'start_time', 'end_time', 'appends', 'resumeCount'));
    }


    //采集企业----------------------------------------------------------------------------------------------------------
    /**
     * 添加企业采集网址
     * @param Request $request
     */
    public function companyAdd(Request $request){
        //获取快速采集登录列表
        if(!empty($request->action)){
            switch($request->action){
                case '58':
                    $source = '58.com';
                    break;
                case 'tzzp':
                    $source = 'tzzp.com';
                    break;
                default:
                    $source = '';
            }
            $collectionLogin = CollectionLogin::where('source', $source)->where('type', '2')->take(10)->orderBy('updated_at')->get();
        }else{
            $collectionLogin = CollectionLogin::where('type', '2')->take(10)->orderBy('updated_at')->get();
        }
        return Style::view('admin.collection.companyAdd', compact('collectionLogin', 'action'));
    }

    /**
     * 开始采集企业
     * @param Request $request
     */
    public function startCompany(CollectionRequest $request){
        $coll_url = !empty($request->url) ? $request->url : '';//采集的地址
        $page = (!empty($request->page) && $request->page <= 100) ? $request->page : 1;//采集的页数
        $resumeArr = [];
        if(strstr($coll_url, "58.com")){
            //存储cookie文件(58同城的cookie)
            $cookie = 'cookie_company_58.txt';
            //检查用户是不是和上个用户相同
            if(!empty($request->username) && !Common::checkUsername($request->username, '58.com', 2)){
                @unlink(storage_path() . '/app/cookie/' . $cookie);//删除cookie
            };
            //检查有没有登录用户
            $check_url = 'https://my.58.com/index/?pp=topbar/';
            $check_login = getCurlCon($check_url, $cookie);
            if(empty($check_login)){
                $username = $request->username;//用户名
                $password = $request->password;//密码
                //登录58同城
                $login_url = 'https://passport.58.com/login/dologin';//登录地址
                //$post_fields = 'source=pc-login&path=http%3A%2F%2Fmy.58.com%2F%3Fpts%3D1493866903712&password=' . $password . '&timesign=&isremember=false&callback=successFun&yzmstate=&fingerprint=87BC65A34C16AC1522DFB544B6A17AE8AF16ED2472C94B5A_011&finger2=zh-CN%7C24%7C1%7C4%7C1920_1080%7C1920_1040%7C-480%7C1%7C1%7C1%7Cundefined%7C1%7Cunknown%7CWin32%7Cunknown%7C5%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7C0_false_false%7Cd41d8cd98f00b204e9800998ecf8427e%7C0d66682378fa3ba7947bdbf9d38c4d4d&tokenId=2096933179&username=' . $username . '&validcode=&vcodekey=&btnSubmit=%E7%99%BB%E5%BD%95%E4%B8%AD...';
                $post_fields = 'source=pc-login&path=http%3A%2F%2Fmy.58.com%2F%3Fpts%3D1502674972962&password=' . $password . '&timesign=&isremember=false&callback=successFun&yzmstate=&fingerprint=449D56111C6DF9ACBC38065E5718ADA6E665DF7AF2D16827_011&finger2=zh-CN%7C24%7C1%7C4%7C1920_1080%7C1920_1040%7C-480%7C1%7C1%7C1%7Cundefined%7C1%7Cunknown%7CWin32%7Cunknown%7C4%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7Cfalse%7C0_false_false%7Cd41d8cd98f00b204e9800998ecf8427e%7C93cb3c44bd5a278d1eb03d59a714b541&tokenId=&token=6idGdCBFxvRhDWtx9GkvXUD45k-mFvtw&username=' . $username . '&validcode=&vcodekey=&btnSubmit=%E7%99%BB%E5%BD%95%E4%B8%AD...';
                getCurlCon($login_url, $cookie, $post_fields, 'POST'); //调用curl保存登录信息
                $check_login = getCurlCon($check_url, $cookie);//设置登录信息
                //添加账号快速登录表
                if(!empty($check_login)){
                    Common::fastLogin($coll_url, $username, $password, '58.com', 2);
                }
            };
            //用户是不是已经登录成功
            if(!empty($check_login)){
                //获取58同城企业列表数据信息 //自定义企业采集列表url地址
                if(preg_match("/(.*)\/pn(\d)+(.*?)/Uis", $coll_url, $arr1)){
                    $list_url = trim($arr1[1], '/') . '/pn' . $page . '/';
                }else{
                    $list_url = trim($coll_url, '/') . '/pn' . $page . '/';
                }
                $listData = getCurlCon($list_url, $cookie);

                //获取企业id和企业详情信息
                $companyInfo = FiveEight::getCompanyInfo($listData);
                if($companyInfo == 'error'){
                    $err_msg = '对不起，采集企业信息出错!';
                    return Style::view('errors.collection', compact('err_msg'));
                }
                //循环企业信息列表
                if(count($companyInfo) > 0){
                    $companyArr = [];
                    foreach($companyInfo as $k => $v){
                        $companyUrl = $v['companyUrl']; //url企业地址
                        //sleep(1);//延迟1秒在页面输出内容
                        //检查企业是不是已经存在
                        if(!DataBase::checkCompany($v['companyId'], '58')){
                            //采集企业数据
                            $arrayCon = FiveEight::companyCon($v['companyId'], $companyUrl, $cookie);
                            if($arrayCon == 'err') continue;// 该企业信息可能不存在了，直接跳过
                            if($arrayCon == 'mq') continue;// 该企业为名企，直接跳过
                            //插入企业数据到临时表
                            $insertData = DataBase::insertCompany($arrayCon, '58');
                            $companyArr[] = $insertData;
                        }else{
                            //更新企业
                            $updateData = DataBase::updateCompany($v['companyId'], $companyUrl, '58', $cookie);
                            $companyArr[] = $updateData;
                        }
                    }
                }
            }else{
                $err_msg = '采集信息出错！登陆用户名或者密码错误，或者该企业信息可能不存在！';
                return Style::view('errors.collection', compact('err_msg'));
            }
        }else if(strstr($coll_url, "tzzp.com")){
            //存储cookie文件(台州招聘的cookie)
            $cookie = 'cookie_company_tzzp.txt';
            //检查用户是不是和上个用户相同
            if(!empty($request->username) && !Common::checkUsername($request->username, 'tzzp.com', 2)){
                @unlink(storage_path() . '/app/cookie/' . $cookie);//删除cookie
            };
            //检查有没有登录用户
            $check_url = 'http://www.tzzp.com/PersonNew/backstage/Index.aspx';
            $check_company_login = getCurlCon($check_url, $cookie);
            if(!preg_match("/<a href=\"(.*)\">\s*<i class=\"bIcon bPhone\"><\/i>(.*)<span><\/span>\s*<\/a>/Uis", $check_company_login, $arr1)){
                $username = $request->username;//用户名
                $password = $request->password;//密码
                //登录台州招聘
                $login_url = 'http://www.tzzp.com/WebService/PersonHandler.ashx';//登录地址
                $post_fields = 'action=Personlogin&userName=' . $username . '&userPwd=' . $password . '&chkPerWeek=false';
                getCurlCon($login_url, $cookie, $post_fields, 'POST'); //调用curl保存登录信息
                $check_company_login = getCurlCon($check_url, $cookie);//设置登录信息
                //添加账号快速登录表
                if(preg_match("/<a href=\"(.*)\">\s*<i class=\"bIcon bPhone\"><\/i>(.*)<span><\/span>\s*<\/a>/Uis", $check_company_login, $arr1)){
                    Common::fastLogin($coll_url, $username, $password, 'tzzp.com', 2);
                }
            }
            //用户是不是已经登录成功
            if(preg_match("/<a href=\"(.*)\">\s*<i class=\"bIcon bPhone\"><\/i>(.*)<span><\/span>\s*<\/a>/Uis", $check_company_login, $arr1)){
                //获取58同城企业列表数据信息 //自定义企业采集列表url地址
                if(preg_match("/(.*)\/page_(\d)+(.*?)/Uis", $coll_url, $arr1)){
                    $list_url = trim($arr1[1], '/') . '/page_' . $page . '.html';
                }else{
                    $list_url = trim($coll_url, '/') . '/page_' . $page . '.html';
                }
                $listData = getCurlCon($list_url, $cookie);
                //获取企业id和企业详情信息
                $companyInfo = Tzzp::getCompanyInfo($listData);
                if($companyInfo == 'error'){
                    $err_msg = '对不起，采集企业信息出错!';
                    return Style::view('errors.collection', compact('err_msg'));
                }
                //循环企业信息列表
                if(count($companyInfo) > 0){
                    $companyArr = [];
                    foreach($companyInfo as $k => $v){
                        $companyUrl = 'http://www.tzzp.com/' . trim($v['companyUrl'], '/'); //url企业地址
                        // sleep(1);//延迟1秒在页面输出内容
                        //检查企业是不是已经存在
                        if(!DataBase::checkCompany($v['companyId'], 'tzzp')){
                            //采集企业数据
                            $arrayCon = Tzzp::companyCon($v['companyId'], $companyUrl, $cookie);
                            if($arrayCon == 'err') continue; //采集信息该页面不存在出错
                            //插入企业数据到临时表
                            $insertData = DataBase::insertCompany($arrayCon, 'tzzp');
                            $companyArr[] = $insertData;
                        }else{
                            //更新企业
                            $updateData = DataBase::updateCompany($v['companyId'], $companyUrl, 'tzzp', $cookie);
                            $companyArr[] = $updateData;
                        }
                    }
                }
            }else{
                $err_msg = '对不起，登陆用户名或者密码错误，或者该用户登录不成功';
                return Style::view('errors.collection', compact('err_msg'));
            }
        }
        $page = $page + 1;//跳转下一页
        $secs = 5;//几秒跳转
        return Style::view('admin.collection.companyInfo', compact('page', 'secs', 'list_url', 'companyArr'));
    }

    /**
     * 临时采集简历列表
     * @param Request $request
     * @return mixed
     */
    public function companyList(Request $request){
        $collectionCompany = CollectionCompany::select('id', 'name', 'address', 'contacts', 'mobile', 'phone')
            ->orderBy('updated_at', 'desc')
            ->paginate(20);
        return Style::view('admin.collection.companyList', compact('collectionCompany'));
    }

    /**
     * 删除企业
     * @param Request $request
     * @return mixed
     */
    public function companyDel(Request $request, $id){
        $result = CollectionCompany::where('id', $id)->delete();
        if($result){
            return response()->json(['status' => 1, 'msg' => '删除账号成功！']);
        }else{
            return response()->json(['status' => 0, 'msg' => '删除账号失败！']);
        }
    }

    //---------------------------------------------------------------------------------------------------------------
    /**
     * 删除采集账号
     * @param Request $request
     * @param $id
     */
    public function delAccount(Request $request, $id){
        $result = CollectionLogin::where('id', $id)->delete();
        if($result){
            return response()->json(['status' => 1, 'msg' => '删除账号成功！']);
        }else{
            return response()->json(['status' => 0, 'msg' => '删除账号失败！']);
        }
    }

    /**
     * 编辑采集账号
     * @param Request $request
     * @param $id
     */
    public function editAccount(Request $request, $id){
        $collectionLogin = CollectionLogin::where('id', $id)->first();
        return Style::view('admin.collection.editAccount', compact('collectionLogin'));
    }

    /**
     * 更新采集账号
     * @param Request $request
     * @param $id
     */
    public function updateAccount(CollectionAccountRequest $request){
        $input = $request->only(['url', 'username', 'password', 'id', 'source']);
        $result = CollectionLogin::where('id', $request->id)->update($input);
        if($result){
            return redirect('admin/resume_add')->with('ok', '更新账号成功');
        }else{
            return redirect('admin/resume_add')->with('ok', '更新账号失败');
        }
    }
}
